from umqtt_simple import MQTTClient
from machine import Pin
from machine import reset
import time, network


def led_flash():
    led = Pin(2, Pin.OUT)
    led.value(0)  # 亮
    time.sleep(0.1)
    led.value(1)  # 灭


def sub_cb(topic, msg):
    global state
    led_flash()
    print((topic, msg))
    if msg == b"on":
        import wakeup
        wakeup.send()
        state = 1
    elif msg == b"off":
        # Pin(2, Pin.OUT).value(1)  # 灭
        state = 0
    elif msg == b"toggle":
        # LED is inversed, so setting it to current state
        # value will make it toggle
        # Pin(2,Pin.OUT).vaue(0) #亮
        state = 1 - state


def umqtt():
    # c = MQTTClient("umqtt_client", "test.mosquitto.org")
    import urandom
    client_id = "umqtt_client_" + str(urandom.getrandbits(30))  # 意外断电，重连加上随机数 解决 [Errno 103] ECONNABORTED MQTT
    print(client_id)
    c = MQTTClient(client_id, "192.168.2.99", port=61613, user="admin", password="password")
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"ledctl")
    print("umqtt success.")
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            c.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep(1)

    c.disconect()


if __name__ == "__main__":
    time.sleep(3)
    try:
        wlan_sta = network.WLAN(network.STA_IF)
        if (wlan_sta.isconnected() == True):
            print("network success.")
            umqtt()
        else:
            print("network error.")
    except Exception as e:
        print("error: {0}".format(e))
        print('reboot after 360s')
        time.sleep(360)
        reset()
